package com.scm.erp.framework.config;

import com.scm.erp.framework.pojo.tUser;
import com.scm.erp.framework.repository.tUserRepository;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * spring-security 链接数据的权限管理
 * */
@Service
public class MyUserDetailsService implements UserDetailsService {
    @Resource
    private tUserRepository userRepository;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User userSecurity = null;
        if("".equals(s.trim())==false || s.equals(null)==false){
            Set<tUser> userSet = userRepository.queryAllByAccount(s);
            for (tUser u:userSet){
                if("".equals(u.toString())==false){
                    if(s.equals(u.getuAccount())==true){
                        userSecurity = new User( u.getuAccount(),u.getuPassword(), u.isEnabled(), u.isAccountNonExpired(), u.isCredentialsNonExpired(), u.isAccountNonLocked(), u.getAuthorities());
                    }
                    if(s.equals(u.getU_Email())==true){
                        userSecurity = new User( u.getU_Email(),u.getuPassword(), u.isEnabled(), u.isAccountNonExpired(), u.isCredentialsNonExpired(), u.isAccountNonLocked(), u.getAuthorities());
                    }
                    if(s.equals(u.getuName())==true){
                        userSecurity = new User( u.getuName(),u.getuPassword(), u.isEnabled(), u.isAccountNonExpired(), u.isCredentialsNonExpired(), u.isAccountNonLocked(), u.getAuthorities());
                    }
                    if(s.equals(u.getuCard())==true){
                        userSecurity = new User( u.getuCard(),u.getuPassword(), u.isEnabled(), u.isAccountNonExpired(), u.isCredentialsNonExpired(), u.isAccountNonLocked(), u.getAuthorities());
                    }
                }
            }
        }
        if(userSecurity==null){
//            throw new UsernameNotFoundException(String.format("没有该用户 '%s'.", s));
        }
        return userSecurity;
    }
}
